<?php
/**
 * Copyright (c) 2013 pipapai.com
 */
JLoader::register("PCompanyModelCompany", OC::$SERVERROOT."/apps/company/lib/company.php");
JLoader::register("PCompanyModelQuota", OC::$SERVERROOT."/apps/company/lib/quota.php");
JLoader::register("PCompanyModelPassword", OC::$SERVERROOT."/apps/company/lib/password.php");
JLoader::register("PCompanyModelLogo", OC::$SERVERROOT."/apps/company/lib/logo.php");
JLoader::register("PCompanyHelper", OC::$SERVERROOT."/apps/company/lib/helper.php");
JLoader::register("PCompanyModelSubAccounts", OC::$SERVERROOT."/apps/company/lib/subaccounts.php");
JLoader::register("PCompanyModelThirdAccounts", OC::$SERVERROOT."/apps/company/lib/thirdaccounts.php");
JLoader::register("PResumesHelper", OC::$SERVERROOT."/apps/resumes/lib/helper.php");
JLoader::register("PJobpositionHelper", OC::$SERVERROOT."/apps/jobposition/lib/helper.php");
JLoader::register("UserPrivacy", JPATH_SITE.'/components/com_puser/userprivacy.php');

class PCompanyController {

   public static function home() {
      if(!PUtil::checkUserLogin(true))
         return;
      
      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      if(PFactory::isMasterUser() && !PCompanyHelper::validateCompanyRegistration()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_employerinfo"));
         return;
      }
      
      // update all jobs jobmanager list
      PCompanyHelper::updateJobManager();
      
      // subaccount can sync too 
      $thirdModel = new PCompanyModelThirdAccounts();
      $sync_info = $thirdModel->getCompanyThirdToolsInfo();
      $thirdaccounts_info = !empty($sync_info['login']) ? json_decode($sync_info['login'],true) : null; 
      $thirdaccounts_status = !empty($sync_info['status']) ? json_decode($sync_info['status'],true) : null;

      if(PFactory::isMasterUser()) {
         $firstlogin = false;
         $app = PFactory::getApplication();
         if(!$app->getUserState("first_login")) {
            $firstlogin = true;
            $app->setUserState("first_login", time());
         }
         $user = PFactory::getMasterUser();
         $user = JobHelper::getEmployerProfileDetails($user->id);
         $session  = PFactory::getSession();
         $first_register = $session->get('first_register');
         
         $model = new PCompanyModelCompany();
         $tmpl = new OCP\Template('company', 'home', 'user');
         $tmpl->assign('page_title', '企业中心');
         $tmpl->assign('totalresumes', $model->getLastResumes(true));
         $tmpl->assign('totalinterview', $model->getLastInterview(true));
         $tmpl->assign('user', $user);
         $tmpl->assign('storage', PResumesHelper::getStorageInfo());
         $tmpl->assign('masteruser', PFactory::isMasterUser());
         $tmpl->assign('firstlogin', $firstlogin);
         $tmpl->assign('resumeforward', $model->getResumeForwardEmail());
         $tmpl->assign('stats', $model->getStats());
         $isset_subdomain = $model->issetSubDomain();
         $tmpl->assign('isset_subdomain', $isset_subdomain);
         $tmpl->assign('thirdaccounts_info',$thirdaccounts_info);
         $tmpl->assign('thirdaccounts_status',$thirdaccounts_status);
         $tmpl->assign('first_register', $first_register);
         $tmpl->printPage();
      }
      else {
         list($starttime, $endtime) = PResumesHelper::getTimeRange();
         $startdate = PFactory::getDate($starttime)->format('Y-m-d H:i:s');
         $enddate = PFactory::getDate($endtime)->format('Y-m-d H:i:s');
         JRequest::setVar('startdate', $startdate);
         JRequest::setVar('enddate', $enddate);

         $isJobManagerViewOnly = PCompanyHelper::isJobManagerViewOnly();

         $model = new PCompanyModelCompany();
         //get masteruser info of subaccount
         $muser=PFactory::getMasterUser();
         $muser = JobHelper::getEmployerProfileDetails($muser->id);
         
         $tmpl = new OCP\Template('company', 'share', 'user');
         $tmpl->assign('isJobManagerViewOnly', $isJobManagerViewOnly);
         if(!$isJobManagerViewOnly){
            $tmpl->assign('totalresumes', $model->getLastResumes(false));
            $tmpl->assign('totalinterview', $model->getLastInterview(false));
         }
         $tmpl->assign('masteruserinfo', $muser);
         $tmpl->assign('user', OC_User::getDisplayName());
         $tmpl->assign('page_title', '企业中心');
         $tmpl->assign('masteruser', false);
         $tmpl->assign('resumeforward', $model->getResumeForwardEmail());
         $tmpl->assign('stats', $model->getStats());
         $tmpl->assign('thirdaccounts_info',$thirdaccounts_info);
         $tmpl->assign('thirdaccounts_status',$thirdaccounts_status);
         $tmpl->printPage();
      }

   }

   public static function termofservice() {
      $tmpl = new OCP\Template('company', 'termofservice', 'base');
      $tmpl->assign('page_title', '枇杷派服务条款');
      $tmpl->printPage();
   }

   public static function registers() {
      if(OC_User::isLoggedIn()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         return;
      }

      if(PUtil::needSSL()) {
         OC_Response::redirect(PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("company_registers")));
         return;
      }

      $tmpl = new OCP\Template('company', 'registers', 'base');
      $tmpl->assign('page_title', '企业注册');
      $tmpl->printPage();
   }

  public static function employerinfo() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         return;
      }

      if(PCompanyHelper::validateCompanyRegistration()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_basicinfo"));
         return;
      }
         
      $tmpl = new OCP\Template('company', 'employerinfo', 'base');
      $tmpl->assign('page_title', '完善企业信息');
      $tmpl->printPage();
   }


   public static function logout() {
      $model = new PCompanyModelCompany();
      $model->logout();
   }

   public static function login() {
      $app = PFactory::getApplication();
      $return = $app->getUserState("return");
      $app->setUserState("return", "");
      if(OC_User::isLoggedIn()) {
         OC_Response::redirect(!empty($return) ? $return : OC_Helper::linkToRoute("company_home"));
         return;
      }

      disableIECache();
      $post = JRequest::get("post");
      //print_r($post);
      if(empty($post) || !empty($post['error'])) {
         if(PUtil::needSSL()) {
            // Should restore $return into session again
            if(!empty($return)) $app->setUserState("return", $return);
            OC_Response::redirect(PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("company_login")));
            return;
         }

         $tmpl = new OCP\Template('company', 'login', 'base');
         $tmpl->assign('page_title', '用户登录');
         $tmpl->assign('postdata', $post);
         if(!empty($return))
            $tmpl->assign('return', $return);
         else 
            $tmpl->assign('return', JArrayHelper::getValue($post, 'return', ''));
         $tmpl->printPage();
         return;
      }

      /* perform the login */
      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelCompany();
      if(!$model->login()) {
         $failtimes = $app->getUserState("login_failed_times", 0);
         $failtimes++;
         $app->setUserState("login_failed_times", $failtimes);
         if(!isAjaxMode()) {
            // redirect to company login page
            $_POST = array();
            header('Location: '. PUtil::getAbsoluteSSLURL("/index.php/apps/company/login"));
            exit;
         }
         
         if($failtimes>3) {     
            $app->setUserState("login_failed_captcha", true);    
            jexit(jsonError($model->getError(),  array('captcha'=>1), false));
         } else
            jexit(jsonError($model->getError(), null, false));
      }
      
      // login is fine, reset login_failed_times
      $app->setUserState("login_failed_times", 0);
      $app->setUserState("login_failed_captcha", false);

      $return = JArrayHelper::getValue($post, 'return', ''); 

      jexit(jsonSuccess('success', (!empty($return) ? $return : PUtil::getAbsoluteSSLURL(OC_Helper::linkToRoute("company_home"))), null, false));
   }

   public static function lostpassword() {
      $tmpl = new OCP\Template('company', 'lostpassword', 'base');
      $tmpl->assign('page_title', '忘记密码?');
      $tmpl->printPage();
   }

   public static function sendpassreset() {
      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelPassword();

      if(!$model->sendPassReset()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess("密码重置链接已经发送到您的邮箱。当您收到邮件，请重新登录。如果您没有收到, 请查看是否被转到了垃圾邮件文件夹。", null, null, false));
   }

   public static function passwdreset() {
      $model = new PCompanyModelPassword();

      $user = $model->getUserFromToken();
      if(!$user) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
         return;
      }

      $tmpl = new OCP\Template('company', 'passwdreset', 'base');
      $tmpl->assign('page_title', '密码重置');
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function setnewpass() {

      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelPassword();
      if(!$model->setNewPass()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('密码设置成功，请使用新密码登录。', null, null, false));
   }

   public static function showcaptcha() {
      $img = new securimage();
     //Change some settings
      $img->image_width = 200;
      $img->image_height = 40;
      $img->code_length = 6;
      $img->num_lines = 0;
      $img->perturbation = 0.55;
      $img->image_signature = str_replace(".com", '', PUtil::serverDomain());
      $img->signature_color = new Securimage_Color('#e1e1e1');
      $img->image_bg_color = new Securimage_Color("#f0f0f0");

      $multi_text_color = array(new Securimage_Color("#3399ff"),
                               new Securimage_Color("#3300cc"),
                               new Securimage_Color("#3333cc"),
                               new Securimage_Color("#6666ff"),
                               new Securimage_Color("#4444aa")
                               );
      $img->text_color = $multi_text_color[rand(0, 4)];

      // don't use use_multi_text as it doesn't align well
      $img->use_multi_text = false;
      $img->charset = '123456789abcdefg';
      $img->show('');
      exit;
   }

   public static function showemptycaptcha() {
      $img = new securimage();
     //Change some settings
      $img->image_width = 200;
      $img->image_height = 40;
      $img->code_length = 6;
      $img->num_lines = 0;
      $img->perturbation = 0.55;
      $img->image_signature = str_replace(".com", '', PUtil::serverDomain());
      $img->signature_color = new Securimage_Color('#e1e1e1');
      $img->image_bg_color = new Securimage_Color("#f0f0f0");

      $multi_text_color = array(new Securimage_Color("#3399ff"),
                               new Securimage_Color("#3300cc"),
                               new Securimage_Color("#3333cc"),
                               new Securimage_Color("#6666ff"),
                               new Securimage_Color("#4444aa")
                               );
      $img->text_color = $multi_text_color[rand(0, 4)];

      // don't use use_multi_text as it doesn't align well
      $img->use_multi_text = false;
      $img->charset = ' ';
      $img->show('');
      exit;
   }

   // get v code
   public static function getvcode() {
      jimport('joomla.mail.helper');
      $receiver = JRequest::getString('receiver', 0);
      if(!$receiver)
         return false;

      OC_JSON::setContentTypeHeader();
      if(JMailHelper::isEmailAddress($receiver)) {
         $app = PFactory::getApplication();
         $code = JobHelper::getEmailVcode($receiver, $app);
         if($code === true)
            jexit(jsonSuccess('success', null, null, false));

         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail(); 
         $config = PFactory::getConfig();
         $receiver = (isDevMode() || isTestMode()) ? $config->get('employeremail', '') : $receiver; 
         $supportmail = $config->get('mailfrom','');
         $body = '<p class="p1"><b>您好！感谢使用枇杷派云招聘，请完成邮箱验证：</b></p>
                  <p class="p3">您的邮箱验证码是：<b>'.$code.'</b></p>
                  <p class="p3 p4">请及时输入收到的验证码，验证码半小时后失效。</p>';

         $mailer->setTemplate('hrsimple');
         $mailer->setVariables(array(
                  'recipient'=>$receiver,
                  'fromName'=>'枇杷派云招聘',
                  'subject'=>'枇杷派云招聘邮箱验证码',
                  'supportmail'=>$supportmail,
                  'hrurl'=>'http://'.OC_Request::serverHost(),
                  'body'=>$body
               )
         );

         $mailer->send();
      }
      else if(JobHelper::isMobilePhone($receiver)) {
         $code = $model->getCode($receiver);
         // send sms via third-party post api
      }

      jexit(jsonSuccess('success', null, null, false));
   }

   // censor reg username
   public static function validatename() {
      OC_JSON::setContentTypeHeader();

      $name = JRequest::getString("name", null);
      if(!$name)
         $name = JRequest::getString("comp_name", null);

      $message = CensorHelper::validateCompanyName($name);
      if($message === true) {
         $model = new PCompanyModelCompany();
         if(!$model->checkUniqueCompanyName($name))
            jexit(json_encode("该公司名称已被使用"));
         else
            jexit(json_encode(true));
      } else
         jexit(json_encode($message));
   }

   // validemail
   public static function validateemail() {
      OC_JSON::setContentTypeHeader();

      $email = JRequest::getString("email", null);

      $message = JobHelper::validateEmail($email);
      if($message === true) {
         if(OC_User::userExists($email))
            $message = "该邮箱地址已经注册";
      }
      
      jexit(json_encode($message));
   }

   // Censor and validate sub_domain
   public static function validatesubdomain() {
      OC_JSON::setContentTypeHeader();

      $sub_domain = JRequest::getString("sub_domain", null);

      $message = CensorHelper::validateSubDomain($sub_domain);
      if($message === true) {
         $model = new PCompanyModelCompany();
         if(!$model->checkUniqueSubDomain($sub_domain))
            jexit(json_encode("域名已被占用"));
         else
            jexit(json_encode(true));
      } else
         jexit(json_encode($message));
   }

   public static function saveregemp() {
      if(OC_User::isLoggedIn())
         jexit();

      $app =  PFactory::getApplication();

      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelCompany();
      $company = $model->register();
      if(!$company) {
         jexit(jsonError($model->getError(), null, false));
      }

      /* the registration is success if we reach here */
      jexit(jsonSuccess('注册成功！', null, null, false));
   }

   public static function saveregdetail() {
      OC_JSON::setContentTypeHeader();

      $user = PFactory::getUser();
      if($user->get("guest")) {
         jexit(jsonError("请先登录", null, false));
      }

      $model = new PCompanyModelCompany();
      if(!$model->saveRegistrationData($user->id)) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function settings() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }      
      
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
     
      $user = PFactory::getUser();

      $user = JobHelper::getEmployerProfileDetails($user->id);
      $model = new PCompanyModelCompany();
      $isset_subdomain = $model->issetSubDomain();

      $tmpl = new OCP\Template('company', 'basicinfo', 'user');
      $tmpl->assign('page_title', '公司信息');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('isset_subdomain', $isset_subdomain);
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }


   public static function summary() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }      
      
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
          
      $user = PFactory::getMasterUser();

      $model = new PCompanyModelCompany(); 
      $user = $model->getProfileSummary($user->id);

      $tmpl = new OCP\Template('company', 'summary', 'user');
      $tmpl->assign('page_title', '公司概况');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function preview() {
      $get_subdomain = JRequest::getString("sub_domain", "");
      $is_jobseeker = JRequest::getString("utp", "");

      $model = new PCompanyModelCompany();
      $company_id = $model->getCompanyId($get_subdomain);

      if ($company_id > 0) {
         $user_id = $company_id;
      } elseif (OC_User::isLoggedIn()) {
         $user = PFactory::getUser();
         $user_id = $user->id;
      } else {
         header('HTTP/1.0 404 Not Found');
         $tmpl = new OCP\Template('', '404', 'guest');
         $tmpl->printPage();
         return;
      }

      $user = JobHelper::getEmployerProfileDetails($user_id, true);
      //external server:check current company if is a testing company,if yes redirect to company home page
      if(!isDevMode() && !isTestMode() && isTestUser($user->email)){
         OC_Response::redirect(OC::$WEBROOT . '/');
         return;
      }

      if(!$user->cb_lastlogondate || $user->cb_lastlogondate == "0000-00-00 00:00:00"){
         $user->lastvisitDate = $user->registerDate;
      }else{
         $user->lastvisitDate = $user->cb_lastlogondate;
      }

      $tmpl = new OCP\Template('company', 'preview', 'base');
      $tmpl->assign('page_title', '公司预览');
      if (!empty($is_jobseeker)) {
         $tmpl->assign('is_jobseeker', true);
      }
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function logo() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }      
      
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
          
      $user = PFactory::getMasterUser();

      $user = JobHelper::getEmployerProfileDetails($user->id);

      $tmpl = new OCP\Template('company', 'logo', 'user');
      $tmpl->assign('page_title', '公司LOGO');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function license() {      
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
          
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         return;
      }
          
      $user = PFactory::getMasterUser();

      $user = JobHelper::getEmployerProfileDetails($user->id);

      $tmpl = new OCP\Template('company', 'license', 'user');
      $tmpl->assign('page_title', '公司验证');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function cloudspace() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }      
      
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
          
      $user = PFactory::getMasterUser();

      $user = JobHelper::getEmployerProfileDetails($user->id);

      $tmpl = new OCP\Template('company', 'cloudspace', 'user');
      $tmpl->assign('page_title', '云端储存空间');
      $tmpl->assign('storage', PResumesHelper::getStorageInfo());
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function subaccounts() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }      
      
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_home"));
         return;
      }

      $user=PFactory::getMasterUser();	  
      $user = JobHelper::getEmployerProfileDetails($user->id);
      if(!isDevMode() && $user->validated!=EMPLOYER_VALIDATED){
         OC_Response::redirect (OC_Helper::linkToRoute("company_license"));
         return; 
      }

      $model = new PCompanyModelSubAccounts;
      $users = $model->getUsers();
      
      $list = new OCP\Template('company', 'part.subaccounts.list', '');
      $list->assign('users', $users);

      $tmpl = new OCP\Template('company', 'subaccounts', 'user');
      $tmpl->assign('page_title', '子账号管理');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('userslist', $list->fetchPage());
      $tmpl->printPage();
   }
   
   public static function quota() {
      if(!OC_User::isLoggedIn()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
         return;
      }
   
      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
   
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
   
      $user=PFactory::getMasterUser();
      $user = JobHelper::getEmployerProfileDetails($user->id);
      if(!isDevMode() && $user->validated!=EMPLOYER_VALIDATED){
         OC_Response::redirect (OC_Helper::linkToRoute("company_license"));
         return;
      }
   
      $model = new PCompanyModelQuota();
      $defaultQuotas = $model->getDefaultQuotas();
   
      $tmpl = new OCP\Template('company', 'quota', 'user');
      $tmpl->assign('page_title', '增值服务管理');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('defaultQuotas', $defaultQuotas);
      $tmpl->printPage();
   }
   
   public static function emailsms() {
      if(!PUtil::checkUserLogin(true))
         return;
       
      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
       
      if(!PFactory::isMasterUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("company_settings"));
         return;
      }
       
      $user=PFactory::getMasterUser();
      $user = JobHelper::getEmployerProfileDetails($user->id);
      if(!isDevMode() && $user->validated!=EMPLOYER_VALIDATED){
         OC_Response::redirect (OC_Helper::linkToRoute("company_license"));
         return;
      }
       
      $tmpl = new OCP\Template('company', 'emailsms', 'user');
      $tmpl->assign('page_title', '短信邮件设置');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->printPage();
   }

   public static function changepassword() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
          
      $user = PFactory::getUser();

      $user = JobHelper::getEmployerProfileDetails($user->id);

      $tmpl = new OCP\Template('company', 'changepassword', 'user');
      $tmpl->assign('page_title', '修改密码');
      $tmpl->assign('masteruser', PFactory::isMasterUser());
      $tmpl->assign('user', $user);
      $tmpl->printPage();
   }

   public static function savesettings() {
      OC_JSON::setContentTypeHeader();

      if(!PFactory::isMasterUser()) {
         jexit("您无权访问该资源");
      }

      $model = new PCompanyModelCompany();
      if(!$model->saveSettings()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function getlogo() {
      if(!PFactory::isMasterUser()) {
         jexit("您无权访问该资源");
      }

      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelLogo();
      if(($logo=$model->getLogo()) === false) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(json_encode($logo));
   }

   public static function uploadlogo() {
      if(!PFactory::isMasterUser()) {
         jexit("您无权访问该资源");
      }

      OC_JSON::setContentTypeHeader('text/plain');
      $model = new PCompanyModelLogo();
      if(($imageid = $model->uploadLogo()) === false) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));

   }

   public static function savelogo() {
      if(!PFactory::isMasterUser()) {
         jexit("您无权访问该资源");
      }

      OC_JSON::setContentTypeHeader();
      $model = new PCompanyModelLogo();
      if(($result = $model->saveLogo()) == false) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, $result, false));
   }

   public static function uploadlicense() {
      if(!PFactory::isMasterUser()) {
         jexit("您无权访问该资源");
      }

      OC_JSON::setContentTypeHeader('text/plain');
      $model = new PCompanyModelCompany();
      jexit($model->uploadLicense());
   }

   public static function setpassword() {
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }

      $model = new PCompanyModelPassword();
      if(!$model->setPassword()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }
   
   public static function setsubdomain() {
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
   	     jexit(jsonError('请先登录', null, false));
   	}

   	if(!PFactory::isMasterUser()) {
         jexit(jsonError('您无权访问该资源', null, false));
      }

      $subdomain = JRequest::getString('sub_domain', null);
      if(empty($subdomain)) {
         jexit(jsonError('请输入您的专属域名!', null, false));
      }    

      $model = new PCompanyModelCompany();
      if(!$model->saveSettings()) {
         jexit(jsonError($model->getError(), null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function synchronousinfo() {
      if(!PUtil::checkUserLogin(true))
         return;
      
      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }
      
      $model = new PCompanyModelThirdAccounts();
      $sync_info = $model->getCompanyThirdToolsInfo();
      if(!$sync_info) 
         $sync_info  = array(); 

      $model2 = new PCompanyModelCompany();
      $resumeforward = $model2->getResumeForwardEmail(); 
      $thirdaccounts_info = !empty($sync_info['login']) ? json_decode($sync_info['login'],true) : null; 
      $thirdaccounts_status = !empty($sync_info['status']) ? json_decode($sync_info['status'],true) : null;

      $userfolderids = PCompanyHelper::getAutoRenewfolderid();

      $autorenewfolderid_51job = !empty($userfolderids['autorenewjobs_51job']) ? $userfolderids['autorenewjobs_51job']: '';
      $autorenewfolderid_zhilian = !empty($userfolderids['autorenewjobs_zhilian']) ?$userfolderids['autorenewjobs_zhilian'] : '';
      $autorenewfolderid_jiancai= !empty($userfolderids['autorenewjobs_jiancai']) ? $userfolderids['autorenewjobs_jiancai']: '';
      $autorenewfolderid_lagou= !empty($userfolderids['autorenewjobs_lagou']) ? $userfolderids['autorenewjobs_lagou']: '';

      $user = PFactory::getMasterUser();
      $user = JobHelper::getEmployerProfileDetails($user->id);
      $synchronousinfoTmp = new OCP\Template('company', 'synchronousinfo', 'user');
      $synchronousinfoTmp->assign('page_title', '同步信息');
      
      $synchronousinfoTmp->assign('masteruser', PFactory::isMasterUser());
      $synchronousinfoTmp->assign('user', $user);
      
      $synchronousinfoTmp->assign('thirdaccounts_info',$thirdaccounts_info);
      $synchronousinfoTmp->assign('thirdaccounts_status',$thirdaccounts_status);
      $synchronousinfoTmp->assign('resumeforwardemail', $resumeforward ? $resumeforward['email'] : '');

      $synchronousinfoTmp->assign('autorenewfolderid_51job',$autorenewfolderid_51job);
      $synchronousinfoTmp->assign('autorenewfolderid_zhilian',$autorenewfolderid_zhilian);
      $synchronousinfoTmp->assign('autorenewfolderid_jiancai',$autorenewfolderid_jiancai);
      $synchronousinfoTmp->assign('autorenewfolderid_lagou',$autorenewfolderid_lagou);
      
      $synchronousinfoTmp->printPage();
   }
   
   public static function savesyncaccount(){
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }
       
      if(PFactory::isJobseekerUser()) {
         jexit(jsonError('您无权访问该资源', null, false));
      }

      $model = new PCompanyModelThirdAccounts();
      if(!$model->saveSyncAccount()) {
         jexit(jsonError($model->getError(), null, false));
      }
       
       jexit(jsonSuccess('保存成功！', null, null, false));
   }
   
   public static function startsyncaccount(){
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }
      
      if(!PSession::checkToken()) {
         jexit(jsonError('登录已失效，请重新登录', null, false));
      }

      if(PFactory::isJobseekerUser()) {
         jexit(jsonError('您无权访问该资源', null, false));
      }

      $username = JRequest::getString('account_username');
      $type = JRequest::getString('type');
      $password = JRequest::getString('account_password');
      $rememberme = JRequest::getInt('rememberme', 0);
      $membername = JRequest::getString('account_membername');
      $jobid = JRequest::getInt('job_id', 0);
      $jobids = array_filter(explode(',',JRequest::getString('jobids','')));
      $captcha = JRequest::getString('captcha'); 
      $syncaction = JRequest::getString('syncaction', '');
      $resumecode = JRequest::getString('resumecode', '');
      $resumecodes = json_decode($resumecode, true);
      $term_id = JRequest::getInt('term_id',0);
      $pageno = JRequest::getInt('pageno',0);

      if(!empty($jobid) && !PCompanyHelper::checkJobManagerPermissions($jobid)) {
         jexit(jsonError('您无权访问该资源', null, false));
      }
      
      if ( !empty($jobids) && !PCompanyHelper::checkJobsManagerPermissions($jobids) ) {
         jexit(jsonError('您无权访问该资源', null, false));
      }

      // for provided account information, backend will overwrite db record it if succeeds - should only overwrite when succeeds 
      // start sync

      if(empty($type)){
         jexit(jsonError('请选择您的第三方招聘网站', null, false));
      }

      if( $captcha != null && empty($captcha) ) {
         jexit(jsonError('请填写验证码', null, false));
      }

      $newcaptcha=''; 
      $model = new PCompanyModelThirdAccounts(); 

      // if $password is empty, we need to obtain from saved record 
      if(empty($password)) {
         $sync_info = $model->getCompanyThirdToolsInfo();
         if(!$sync_info) 
            $sync_info  = array(); 
         
         $thirdaccounts_info = !empty($sync_info['login']) ? json_decode($sync_info['login'],true) : null;
         $password = !empty($thirdaccounts_info[$type]) ? PCompanyHelper::decrypt($thirdaccounts_info[$type]['password']) : ''; 
         // the password might have control chars after decrypt if it's encrypted by nodejs
         $password = preg_replace("/[[:cntrl:]]/", "", $password);

         // if the saved password is not empty, set rememberme is 1 by default. rememberme cannot be 0 in this case anyway 
         $rememberme = 1; 
      }

      $jobid_arr = array();
      if (!empty($jobid)) {
         $ids = PJobpositionHelper::getGroupsJobsId($jobid);
         $jobid_arr = $ids ? JArrayHelper::getColumn($ids, 'id') : array($jobid);
         $param = array('jobids'=>$jobid_arr);
      } elseif (!empty($term_id)) {
         $param = array('tid'=>$term_id, 'pageno'=>$pageno);
      } elseif (!empty($resumecode)) {
         $param = array('resumecodes'=>$resumecodes);
      } elseif (!empty($jobids)) {
         $param = array('jobids'=>$jobids);
      } else {
         $param = array();
      }

      $status = $model->startSync($type, explode(",", $syncaction), 
                                  array('username'=>$username, 
                                        'membername'=>$membername,
                                        'password'=>$password,
                                        'rememberme'=>$rememberme,
                                        'captcha'=> $captcha),
                                         $param, $newcaptcha);

      if($status === false) {
         jexit(jsonError($model->getError(), null, false));
      }
      else if($status == 'task-add-to-background' || $status == 'hidden-task-add-to-background') {
         jexit(jsonSuccess($status, null, null, false));
      }
      else if($status == 'login-success' || $status == 'trylogin-success') {
         jexit(jsonSuccess($status, null, null, false));
      }
      else if ($status == 'captcha-reload') {
         // need to replace new captcha
         jexit(jsonError('登录失败！验证码或密码错误', array('captcha'=>$newcaptcha), false));
      }
      

      jexit(jsonSuccess('success', null, null, false));
   }
   
   public static function uploadreceipt() {
      OC_JSON::setContentTypeHeader('text/plain');
      $model = new PCompanyModelQuota();
      
      if($model->uploadReceipt()) {
         jexit(jsonSuccess('上传成功！', null, null, false));
      } else {
         jexit(jsonError($model->getError() ? $model->getError() : '上传失败', null, false));
      }
   }

   public static function setautoaction(){
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }

      if(!PSession::checkToken()) {
         jexit(jsonError('登录已失效，请重新登录', null, false));
      }

      if(PFactory::isJobseekerUser()) {
         jexit(jsonError('您无权访问该资源', null, false));
      }

      $type = JRequest::getString('type','');
      $syncaction = JRequest::getString('syncaction','');

      $model = new PCompanyModelThirdAccounts();

      if(!$model->RemoveAutoActions($syncaction,$type)) {
         jexit(jsonError($model->getError(), null, false));
      }

      if(!$model->addAutoAction($syncaction,$type)) {
         jexit(jsonError($model->getError(), null, false));
      }
       
      jexit(jsonSuccess("success", null, null, false));
   }
   
}
